import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    """
    合并请求用户的购物车数据，将未登录保存在cookie里的保存到redis中
    遇到cookie与redis中出现相同的商品时以cookie数据为主，覆盖redis中的数据
    :param request: 用户的请求对象
    :param user: 当前登录的用户
    :param response: 响应对象，用于清楚购物车cookie
    :return:
    """
    # 获取ｃｏｏｋｉｅ
    cart_cookie = request.COOKIES.get('cart_cookie')

    # 判断ｃｏｏｋｉｅ是否存在
    if not cart_cookie:
        # 不存在，直接返回
        return response

    # 解密ｃｏｏｋｉｅ
    cart = pickle.loads(base64.b64decode(cart_cookie.encode()))

    # 拆分数据
    data_dict = {}
    # 选中状态
    cart_selected = []
    # 未选中状态
    cart_selected_no = []

    if cart:

        for sku_id, count_dict in cart.items():
            data_dict[int(sku_id)] = int(count_dict['count'])

            if count_dict['selected']:
                cart_selected.append(int(sku_id))
            else:
                cart_selected_no.append(int(sku_id))

        # 写入ｒｅｄｉｓ
        conn = get_redis_connection('cart')

        # 写入ｈａｓｈ
        conn.hmset('cart_%s' % user.id, data_dict)

        # 写入选中状态
        if cart_selected:
            conn.sadd('cart_selected_%s' % user.id, *cart_selected)

        # 删除未选中的ｓｋｕ＿Ｉｄ
        if cart_selected_no:
            conn.srem('cart_selected_%s' % user.id, *cart_selected_no)

        response.delete_cookie('cart_cookie')

    return response
